package com.ruoyi.web.controller.seal;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.RoleConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.seal.domain.Seal;
import com.ruoyi.seal.service.ISealService;
import com.ruoyi.system.service.ISysCommonService;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 用印Controller
 *
 * @author 钟彧
 * @date 2022-08-08
 */
@RestController
@RequestMapping("/seal")
public class SealController extends BaseController {

    @Autowired
    private ISealService sealService;

    @Autowired
    private ISysCommonService sysCommonService;

    @Autowired
    private ISysUserService sysUserService;

    /**
     * 查询自身用印列表
     */
    @PreAuthorize("@ss.hasPermi('seal:seal:list')")
    @GetMapping("/list")
    public TableDataInfo list(Seal seal) {
        startPage();
        if (SecurityUtils.isAdmin(getUserId())) {
            List<Seal> list = sealService.selectSealList(seal);
            return getDataTable(list);
        }
        seal.setUserId(getUserId());
        List<Seal> list = sealService.selectSealList(seal);
        return getDataTable(list);
    }

    /**
     * 科室负责人查询用印列表
     */
    @PreAuthorize("@ss.hasPermi('seal:dept:list')")
    @GetMapping("/deptList")
    public TableDataInfo deptList(Seal seal) {
        startPage();
        seal.setDeptMasterId(getUserId());
        List<Seal> list = sealService.selectSealListByDept(seal);
        return getDataTable(list);
    }

    /**
     * 获取自身用印详细信息
     */
    @PreAuthorize("@ss.hasPermi('seal:seal:query')")
    @GetMapping(value = "/{sealId}")
    public AjaxResult getInfo(@PathVariable("sealId") String sealId) {
        if (SecurityUtils.isAdmin(getUserId())) {
            return AjaxResult.success(sealService.selectSealBySealId(sealId, null));
        }
        return AjaxResult.success(sealService.selectSealBySealId(sealId, getUserId()));
    }

    /**
     * 修改用印
     */
    @PreAuthorize("@ss.hasPermi('seal:seal:updateSelfSeal')")
    @PostMapping("/updateSelfSeal")
    public AjaxResult updateSelfSeal(@RequestBody Seal seal) {

        if (SecurityUtils.isAdmin(getUserId())) {
            if (sealService.selectSealBySealId(seal.getSealId(), getUserId()) != null) {
                return sealService.updateSeal(seal) > 0 ? AjaxResult.success("修改成功") : AjaxResult.error("修改失败");
            } else {
                return AjaxResult.error("当前为管理员账户，请使用申请该用印记录账户修改");
            }
        }

        Seal findSeal = sealService.selectSealBySealId(seal.getSealId(), getUserId());
        if (findSeal != null) {
            if (findSeal.getDeleted() == 0||findSeal.getDeleted() == 4) {
                seal.setDeptMaster(sysUserService.selectUserById(seal.getDeptMasterId()).getNickName());
                seal.setSealMaster(sysUserService.selectUserById(seal.getSealMasterId()).getNickName());
                return sealService.updateSeal(seal) > 0 ? AjaxResult.success("修改成功") : AjaxResult.error("修改失败");
            } else if (findSeal.getDeleted() == 1||findSeal.getDeleted() == 5) {
                return AjaxResult.error("已进入审批流程，无法修改");
            } else if (findSeal.getDeleted() == 2) {
                return AjaxResult.error("审批已完成，无法修改");
            } else if (findSeal.getDeleted() == 3) {
                return AjaxResult.error("当前申请已取消，无法修改");
            }
        } else {
            return AjaxResult.error("修改失败：非法修改");
        }
        return null;
    }

    /**
     * 科室负责人获取用印详细信息
     */
    @PreAuthorize("@ss.hasPermi('seal:dept:query')")
    @GetMapping(value = "/deptList/{sealId}")
    public AjaxResult getInfoByDept(@PathVariable("sealId") String sealId) {
        Seal seal = new Seal();
        seal.setSealId(sealId);
        seal.setDeptMasterId(getUserId());
        sealService.intoApprovel(seal);
        return AjaxResult.success(sealService.selectSealBySealIdAndApproveId(seal));
    }

    /**
     * 指定审批人获取用印详细信息
     */
    @PreAuthorize("@ss.hasPermi('seal:sealMaster:query')")
    @GetMapping(value = "/sealMasterList/{sealId}")
    public AjaxResult getInfoBySealMaster(@PathVariable("sealId") String sealId) {
        Seal seal = new Seal();
        seal.setSealId(sealId);
        seal.setSealMasterId(getUserId());
        return AjaxResult.success(sealService.selectSealBySealIdAndApproveId(seal));
    }

    /**
     * 科室负责人审批
     * todo 流水号过滤
     */
    @PreAuthorize("@ss.hasPermi('seal:dept:approval')")
    @Log(title = "科室审批", businessType = BusinessType.INSERT)
    @PostMapping("/deptApproval")
    public AjaxResult deptApproval(@RequestBody Seal seal) {
        if (sealService.selectSealBySealIdAndApproveId(seal).getDeleted() == 3) {
            return AjaxResult.error("用户已取消，无需审核");
        }
        if(!sealService.selectSealBySealIdAndApproveId(seal).getSealIdea().equals("0")){
            return AjaxResult.error("审批失败：负责人已进行审批");
        }
        seal.setDeptMasterId(getUserId());
        int count = sealService.deptApprovalSeal(seal);
        if (count > 0) {
            return AjaxResult.success();
        } else {
            return AjaxResult.error("审批失败：非法审批或无权限");
        }
    }

    /**
     * 新增用印
     */
    @PreAuthorize("@ss.hasPermi('seal:seal:add')")
    @Log(title = "申请用印", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Seal seal) {
        seal.setUserId(getUserId());
        seal.setDeptMaster(sysUserService.selectUserById(seal.getDeptMasterId()).getNickName());
        seal.setSealMaster(sysUserService.selectUserById(seal.getSealMasterId()).getNickName());
        return toAjax(sealService.insertSeal(seal));
    }

    /**
     * 申请时自动带出：
     * 用印类型/申请人姓名/申请人部门/用印审批人
     */
    // TODO: 2022-09-03 自动带出科室负责人
    @GetMapping("/querySealType")
    public AjaxResult querySealType() {
        HashMap<String, Object> map = new HashMap<>();
        map.put("sealType", sealService.querySealType());
        map.put("deptName", sysCommonService.getDeptName(getDeptId()));
        map.put("nickName", sysCommonService.getUserName(getUserId()));
        //权限菜单获取用印审批人下拉列表
        map.put("sealMaster", sysCommonService.getSealMsterList());
        //权限菜单获取科室审批人下拉列表
        map.put("deptMaster", sysCommonService.getSealDeptMaster(getDeptId()));
        return AjaxResult.success(map);
    }

    /**
     * 删除用印
     */
    @PreAuthorize("@ss.hasPermi('seal:seal:remove')")
    @Log(title = "取消用印", businessType = BusinessType.DELETE)
    @DeleteMapping("/{sealIds}")
    public AjaxResult remove(@PathVariable String[] sealIds) {
        int count = sealService.deleteSealBySealIds(sealIds, getUserId());
        if (count > 0) {
            return AjaxResult.success("取消成功");
        } else {
            if (SecurityUtils.isAdmin(getUserId())) {
                return AjaxResult.error("当前为管理员账户，请使用申请该用印记录账户取消");
            } else {
                return AjaxResult.error("当前申请已进入审核流程或完成审核，无法取消");
            }
        }
    }


    /**
     * 导出用印列表
     */
    @PreAuthorize("@ss.hasPermi('seal:seal:export')")
    @Log(title = "用印", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Seal seal) {
        System.out.println(seal.toString());
        List<Seal> list = sealService.selectSealList(seal);
        ExcelUtil<Seal> util = new ExcelUtil<Seal>(Seal.class);
        util.exportExcel(response, list, "用印数据");
    }

    /**
     * 导出个人选中用印列表
     */
    @PreAuthorize("@ss.hasPermi('seal:seal:exportOwnSelectedSealList')")
    @Log(title = "用印", businessType = BusinessType.EXPORT)
    @PostMapping("/exportOwnSelectedSealList")
    public void exportOwnSelectedSealList(HttpServletResponse response, Seal seal) {
        if (SecurityUtils.isAdmin(getUserId())) {
            List<Seal> listSealByIds = sealService.getListSealByIds(seal.getIds());
            ExcelUtil<Seal> util = new ExcelUtil<Seal>(Seal.class);
            util.exportExcel(response, listSealByIds, "用印数据");
        } else if (sealService.isSelfSealList(seal.getIds(), getUserId())) {
            List<Seal> listSealByIds = sealService.getListSealByIds(seal.getIds());
            ExcelUtil<Seal> util = new ExcelUtil<Seal>(Seal.class);
            util.exportExcel(response, listSealByIds, "用印数据");
        }
    }

    /**
     * 指定负责人查询用印列表
     */
    @PreAuthorize("@ss.hasPermi('seal:master:list')")
    @GetMapping("/masterList")
    public TableDataInfo masterList(Seal seal) {
        startPage();
        seal.setSealMasterId(getUserId());
        seal.setDeptIdea("1");
        List<Seal> list = sealService.selectSealListByMaster(seal);
        return getDataTable(list);
    }

    /**
     * 指定用印审批人审批
     */
    @PreAuthorize("@ss.hasPermi('seal:master:approval')")
    @Log(title = "指定审批人审批", businessType = BusinessType.INSERT)
    @PostMapping("/masterApproval")
    public AjaxResult masterApproval(@RequestBody Seal seal) {
        seal.setSealMasterId(getUserId());
        int count = sealService.masterApproval(seal);
        //设置状态：完成审批
        if (count > 0) {
            return AjaxResult.success();
        } else {
            return AjaxResult.error("审批失败：非法审批或无权限");
        }
    }

    /**
     * 补传附件
     */
    @PreAuthorize("@ss.hasPermi('seal:seal:reUpFile')")
    @Log(title = "用印附件补传", businessType = BusinessType.UPDATE)
    @PostMapping("/reUpFile")
    public AjaxResult reUpFile(@RequestBody Seal seal) {
        if (StringUtils.isNotEmpty(seal.getSealId())) {
            if (sealService.isSelfSeal(seal.getSealId(), getUserId()) > 0) {
                if (sealService.selectSealBySealId(seal.getSealId(), getUserId()).getDeleted() == 2) {
                    return sealService.reUpFile(seal) > 0 ? AjaxResult.success("补传成功") : AjaxResult.error("补传失败");
                } else {
                    return AjaxResult.error("请在审核完成后进行附件补传");
                }
            } else {
                if (SecurityUtils.isAdmin(getUserId())) {
                    return AjaxResult.error("当前账户为管理员账户，请联系该申请员工进行附件上传");
                } else {
                    return AjaxResult.error("上传失败：非法上传");
                }
            }
        } else {
            return AjaxResult.error("上传失败：请联系管理员");
        }
    }
}
